package com.example.demo.thread;

import java.util.concurrent.*;

/**
 * FutureTask实现了Future接口，将一个Callable实例作为参数传给它，就能创建一个FutureTask实例，
 * 然后用ExecutorService的submit方法来执行这个实例。最后同样是用get方法获取线程执行后的结果。
 *
 * @author luowj12
 * @since 2021/4/1 10:46
 */
public class TestFutureTask {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Callable task = new Callable() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 100; i++) {

                    sum += i;
                }
                return sum;
            }
        };
        //executor.submit(task);
        FutureTask ft = new FutureTask(task);
        executor.submit(ft);
        System.out.println(ft.get());
        executor.shutdown();
    }
}
